<?php
class CategoryAction extends AdminPublicAction{

/*======================================================================
	分類列表
======================================================================================*/
	public function index(){
		
		import('Class.Category', APP_PATH);
		$cate = D('CategoryRelation')->relation(true)->order('sort_order', 'ASC')->select();
		$new_cate = Category::unlimitedForLayer($cate);
		$str  =  Category::unlimitedForLayer2($new_cate);
		
		if (S("success") != "")
			{
				$this->assign("msg", '<div class="success">'.S("success").'</div>');
				S('success',NULL);
			}
			
			if (S("err") != "")
			{
				$this->assign("msg", '<div class="err">'.S("err").'</div>');
				S('err',NULL);
			}		
		$this->assign('content',$str);
		$this->li1 = 'current';
		$this->left_category = 'current';
		$this->display();
	}
/*======================================================================
	添加分類 & 編輯分類
======================================================================================*/
	public function detail(){
			
			import('Class.Category', APP_PATH);
				
			$langList = explode(",", C('LANG_LIST'));
			$lang = array();
			foreach($langList as $item)
			{
				$langTxt = '';
				if ($item == 'tchinese') $langTxt = '繁體';
				if ($item == 'schinese') $langTxt = '简体';
				if ($item == 'english')  $langTxt = 'English';
				$lang[] = array("value" => $item, 'txt'=> $langTxt );			
			}	
			$id = I('id','',intval);
			if(is_numeric($id) && tep_not_null($id)){
				
				$listing = D('CategoryView')->getOne(array('c.categories_id' => $id,'cd.language_id' => (int)L('lan_id')));	
				$cateToLang = D('CategoryView')->getAll(array('c.categories_id' =>$id)); //獲取多語言信息.
				foreach ($cateToLang as $value)
					{				
						$titleArr[$value['language_id']]   =   $value['categories_name'];
						$descArr[$value['language_id']]    =   $value['categories_description'];
					}
				
				$cate = Category::tep_get_category_tree(0,'',$listing['categories_id']);
				
				if ( isset($listing["categories_image"]) && $listing["categories_image"] != '')
				{
					$imageShow = '<input type="hidden"  name="del_iamge" value="flase" />
								  <div id="image">
								  <a  href="'.__ROOT__.'/Public/images/categories/thumb/m_'.$listing["categories_image"].'" class="fancyBox"><img src="'.__ROOT__.'/Public/images/categories/thumb/m_'.$listing["categories_image"].'" width="200"></a><br /><a  href="#" onclick="delImages();return false;"  class="del">Delete</a></div>';
				}	
				$this->listing = $listing;	
				$this->titleArr = $titleArr;
				$this->descArr = $descArr;
				$this->cate = $cate;
				$this->imageShow = $imageShow;
				$this->action = 'editHandle';
				$this->actionName = 'Save';
			}else{
				$cate = Category::tep_get_category_tree();
				$this->cate = $cate;
				$this->action = 'addHandle';
				$this->actionName = 'add';
			}
			$this->lang = $lang;
			$this->langList = $langList;
			$this->left_category = 'current';
			$this->display();
			
		}
/*======================================================================
	添加分類處理
======================================================================================*/
	public function addHandle(){
		if(IS_POST){
			$data['parent_id'] = I('post.pid');
			$data['date_added'] = date("Y-m-d");
			$data['categories_status'] = I('post.categories_status',0,'intval');
			$data['sort_order'] = I('post.sort_order');
			$categories = M("categories");
			$insertId = $categories->add($data);		
			
			$language = explode(",", C('LANG_LIST'));
			$i = 0;
			$map = array();
			foreach( $language as $item)
			{
				$i++;
				$map['categories_id'] = $insertId;
				$map['language_id']  = $i;
				$map['categories_name'] =  I('post.categories_name_'.$i);
				$map['categories_description'] = tep_db_prepare_input(I('post.categories_description_'.$i));
				M("categories_description")->add($map);
			}	
			if ($_FILES['categories_image']['error'] == 0)
			{
				//上传图片
				import('@.ORG.UploadFile');
				$upload = new UploadFile('categories_image');
					//设置上传文件大小 
				$upload->maxSize            = 6000000;
					//设置上传文件类型
				$upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
					//设置附件上传目录
				$upload->savePath 			=  './Public/images/categories/';
					//设置需要生成缩略图，仅对图像文件有效
				$upload->thumb              = true;
					// 縮略圖路徑
				$upload->thumbPath         =  './Public/images/categories/thumb/';
				// 设置引用图片类库包路径
				$upload->imageClassPath     = '@.ORG.Image';
					//设置需要生成缩略图的文件后缀
				$upload->thumbPrefix        = 'm_,s_';  //m_大缩略图，s_小缩略图
					//设置缩略图最大宽度
				$upload->thumbMaxWidth      = '300,100';
					//设置缩略图最大高度
				$upload->thumbMaxHeight     = '300,100';
					//设置上传文件规则
				$upload->saveRule           = 'uniqid';
				if(!$upload->upload()) 
				{			
					S('err','image save failed! '.$upload->getErrorMsg());				
					$this->redirect('index');
				}
				else
				{
					$info =  $upload->getUploadFileInfo();
					M("categories")->where(array("categories_id" => $insertId))->setField('categories_image',$info[0]['savename']);	;
					S('success','Category successfully added!');			
					$this->redirect('index');			
				}
			}else{
				 	S('success','Category successfully added!');			
					$this->redirect('index');	
			}
		}else{
			$this->redirect('index');
		}				
		
	}

/*======================================================================
	編輯分類處理
======================================================================================*/
	public function editHandle(){
		if(IS_POST){
			
			$id =  I('post.categories_id');
			$data['parent_id'] = I('post.pid');
			$data['date_added'] = date("Y-m-d");
			$data['categories_id'] = I('post.categories_id');
			$data['categories_status'] = I('post.categories_status',0,'intval');
			$data['sort_order'] = I('post.sort_order');
			M("categories")->save($data);		
			
			$language = explode(",", C('LANG_LIST'));
			$i = 0;
			$map = array();
			foreach( $language as $item)
			{
				$i++;
				$map['categories_name'] = I('post.categories_name_'.$i);
				$map['categories_description'] = tep_db_prepare_input(I('post.categories_description_'.$i));
				M('categories_description')->where(array('categories_id'=> $id,'language_id' => $i))->save($map);
			}
			
				
			if ($_FILES['categories_image']['error'] == 0)
			{
				//上传图片
				import('@.ORG.UploadFile');
				$upload = new UploadFile('categories_image');
					//设置上传文件大小 
				$upload->maxSize            = 6000000;
					//设置上传文件类型
				$upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
					//设置附件上传目录
				$upload->savePath 			=  './Public/images/categories/';
					//设置需要生成缩略图，仅对图像文件有效
				$upload->thumb              = true;
					// 縮略圖路徑
				$upload->thumbPath         =  './Public/images/categories/thumb/';
				// 设置引用图片类库包路径
				$upload->imageClassPath     = '@.ORG.Image';
					//设置需要生成缩略图的文件后缀
				$upload->thumbPrefix        = 'm_,s_';  //m_大缩略图，s_小缩略图
					//设置缩略图最大宽度
				$upload->thumbMaxWidth      = '300,100';
					//设置缩略图最大高度
				$upload->thumbMaxHeight     = '300,100';
					//设置上传文件规则
				$upload->saveRule           = 'uniqid';
				if(!$upload->upload()) 
				{			
					S('err','image save failed! '.$upload->getErrorMsg());
					$this->redirect('index');
				}
				else
				{
					$image = M("categories")->where(array("categories_id" => $id))->getField('categories_image');
					@unlink("./Public/images/categories/".$image);
					@unlink("./Public/images/categories/thumb/s_".$image);
					@unlink("./Public/images/categories/thumb/m_".$image);
					$info =  $upload->getUploadFileInfo();
					M("categories")->where(array("categories_id" => $id))->setField('categories_image',$info[0]['savename']);
					
								
				}
			}
			else
			{
				if (isset($_POST['del_iamge']) && $_POST['del_iamge'] == 'true')
				{
					$image = M("categories")->where(array("categories_image" => $id))->getField('categories_image');
					@unlink("./Public/images/categories/".$image);
					@unlink("./Public/images/categories/thumb/s_".$image);
					@unlink("./Public/images/categories/thumb/m_".$image);
					M("categories")->where(array('categories_id' => $id))->setField('categories_image','');
				}
			}	
			S('success','Category update successfully!');
			$this->redirect('index');
		}else{
			$this->redirect('index');	
		}
	}
/*======================================================================
	分類刪除
======================================================================================*/
	public function deleteCate(){
		$id = I('id');
		
		if(tep_not_null($id) && is_numeric($id)){	
			$img = M('categories')->where(array('categories_id' => $id))->field('categories_image')->find();
			@unlink("./Public/images/categories/".$img['categories_image']);
			@unlink("./Public/images/categories/m_".$img['categories_image']);
			@unlink("./Public/images/categories/s_".$img['categories_image']);
			import('Class.Category', APP_PATH);
			$cate = D('CategoryRelation')->relation(true)->order('sort_order', 'ASC')->select();
			$cate = Category::getChildsId($cate,$id);
			foreach($cate as $v){
				$Pimg = M('categories')->where(array('categories_id' => $v))->field('categories_image')->select();
				foreach($Pimg as $value){
					@unlink("./Public/images/categories/".$value['categories_image']);
					@unlink("./Public/images/categories/thumb/s_".$value['categories_image']);
					@unlink("./Public/images/categories/thumb/m_".$value['categories_image']);
				}	
				M('categories')->where(array('categories_id' => $v))->delete();
				M('categories_description')->where(array('categories_id' => $v))->delete();
				M('products_to_categories')->where(array('categories_id' => $v))->delete();
				
			}	
			M('categories')->where(array('categories_id' => $id))->delete();
			M('categories_description')->where(array('categories_id' => $id))->delete();
			M('products_to_categories')->where(array('categories_id' => $id))->delete();
			S('success','Category deleted successfully!');
			$this->redirect('index');
		}else{
			$this->redirect('index');
			}
	}	
/*======================================================================
	分類修改顯示
======================================================================================*/
	public function changeStatus(){			
			$check = M("categories")->where(array("categories_id" => (int)$_GET['id']))->getField('categories_status');	
			$categories_status = ($check == 1)?0:1;		
			M("categories")->where("categories_id=".(int)$_GET['id'])->setField('categories_status',$categories_status);
			echo (int)$categories_status;					
			
	}


}

?>
